package cn.chiship.bs.api.core.config;

import cn.chiship.bs.api.core.util.ServletUtil;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.exception.ExceptionUtil;
import cn.chiship.sdk.core.exception.custom.BusinessException;
import cn.chiship.sdk.core.exception.custom.PermissionsException;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.bs.api.biz.service.UserCacheService;
import cn.chiship.bs.api.core.exception.FrameworkBuildException;
import cn.chiship.bs.api.core.util.BindingResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用@ControllerAdvice+@ExceptionHandler统一处理异常
 * controller中不需捕获异常
 *
 * @author lijian
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final String REQUEST_ID = "requestId";
    private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
    private static final String STRING_METHOD_NAME = "methodName";


    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @Resource
    private UserCacheService userCacheService;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<BaseResult> validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        BaseResult baseResult = BindingResultUtil.format(result);
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<BaseResult> validationRequestParameterException(MissingServletRequestParameterException exception) {
        Map<String, Object> errorMap =  new HashMap<>(2);
        errorMap.put(exception.getParameterName(), "缺少[" + exception.getParameterType() + "]类型参数[" + exception.getParameterName() + "]");
        BaseResult baseResult = BaseResult.error(BaseResultEnum.PARAM_CHECK_FAILED, errorMap);
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }


    @ExceptionHandler({BusinessException.class, PermissionsException.class})
    public ResponseEntity<BaseResult> handleBusinessException(BusinessException exception) {
        BaseResult baseResult = ExceptionUtil.formatException(exception);
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }

    /**
     * 业务异常外的所有Exception
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    public ResponseEntity<BaseResult> handleException(Exception e) {
        e.printStackTrace();
        HttpServletRequest request = ServletUtil.getRequest();
        String requestId = null;
        if (!StringUtil.isNull(request.getAttribute(REQUEST_ID))) {
            requestId = request.getAttribute(REQUEST_ID).toString();
        }

        BaseResult baseResult = new FrameworkBuildException().buildException(requestId, e);
        return new ResponseEntity<>(baseResult, HttpStatus.OK);
    }
}
